package com.symaster.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTool {

    private final File srcFolder; // 被压缩的目标
    private final File dstName;    // 压缩后的目录及文件名

    public static void main(String[] args) {
        ZipTool zipTool = new ZipTool(new File("D:\\test\\TIF文件"), new File("D:\\test\\tif.zip"));

    }

    public ZipTool(File srcFolder, File dstPath) {
        this.srcFolder = srcFolder;
        this.dstName = dstPath;
        start();
    }

    public void start() {
        try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(dstName.toPath()))) {
            File[] listFile = srcFolder.listFiles(); // 对输入目录进行查看
            assert listFile != null;
            for (File o : listFile) {
                writeFile(o, out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写文件
     */
    public void writeFile(File f, ZipOutputStream out) {
        try {
            if (f.isDirectory()) {
                File[] listFile = f.listFiles();
                if (listFile == null || listFile.length == 0) {
                    String s = f.toString().substring(3);
                    out.putNextEntry(new ZipEntry(s + " " + "/"));
                } else {
                    for (File oo : listFile) {
                        writeFile(oo, out);
                    }
                }
            } else {
                InputStream in = new BufferedInputStream(Files.newInputStream(f.toPath()));
                int len;
                byte[] b = new byte[8192];
                String s = f.toString().substring(3);
                out.putNextEntry(new ZipEntry(s));
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}